﻿using System;
using System.IO;
using System.Threading.Tasks;
using System.Xml.Linq;
using System.Runtime.CompilerServices;

using Windows.Storage;
using Windows.Storage.Streams;
using Windows.Networking.BackgroundTransfer;

using SeriesManager.Enum;
using SeriesManager.Extension;

namespace SeriesManager.Model.Banner
{
    public class BannerBaseModel : BindableBase
    {
        #region Properties

        private static readonly string BannerPath = "http://thetvdb.com/banners/";

        private int id;
        private readonly int seriesID;
        private string localPath = null;
        private string remotePath;
        private double rating;
        private int ratingCount;
        private Languages language;
        private bool loading;
        private bool loaded;

        public bool Loading
        {
            get
            {
                return this.loading;
            }
            protected set
            {
                base.SetProperty(ref this.loading, value);
            }
        }

        public int ID
        {
            get
            {
                return this.id;
            }
            set
            {
                base.SetProperty(ref this.id, value);
            }
        }

        public string RemotePath
        {
            get
            {
                return this.remotePath;
            }
            set
            {
                base.SetProperty(ref this.remotePath, value);
            }
        }

        public string LocalPath
        {
            get
            {
                Dwl();
                return this.localPath;
            }
            set
            {
                base.SetProperty(ref this.localPath, value);
            }
        }

        public double Rating
        {
            get
            {
                return this.rating;
            }
            set
            {
                base.SetProperty(ref this.rating, value);
            }
        }

        public int RatingCount
        {
            get
            {
                return this.ratingCount;
            }
            set
            {
                base.SetProperty(ref this.ratingCount, value);
            }
        }

        public Languages Language
        {
            get
            {
                return this.language;
            }
            set
            {
                base.SetProperty(ref this.language, value);
            }
        }

        #endregion

        #region Contructor

        public BannerBaseModel(int seriesID)
        {
            this.seriesID = seriesID;
        }

        public BannerBaseModel(int seriesID, int bannerID) : this(seriesID)
        {
            this.id = bannerID;
        }

        public BannerBaseModel(int seriesID, string remotePath) : this(seriesID)
        {
            this.remotePath = remotePath;
        }

        #endregion

        private void Dwl()
        {
            if (!loaded && !loading)
            {
                this.Loading = true;
                this.Download(this.remotePath).ContinueWith(T => 
                {
                    try
                    {
                        this.LocalPath = T.Result;
                        this.loaded = true;
                    }
                    catch
                    {
                        this.loaded = false;
                    }
                    this.Loading = false;
                }, TaskContinuationOptions.ExecuteSynchronously);
            }       
        }

        public async Task DownloadImage()
        {
            if (!loaded && !loading)
            {
                this.Loading = true;
                try
                {
                    this.LocalPath = await Download(this.remotePath);
                    this.loaded = true;
                }
                catch
                {
                    this.loaded = false;
                }
                this.Loading = false;
            }            
        }

        protected async Task<string> Download(string remotePath, bool thumb = false)
        {
            if (string.IsNullOrWhiteSpace(remotePath))
            {
                return null;
            }

            var fileName = Path.GetFileName(remotePath);
            if (thumb)
            {
                fileName = "thumb_" + fileName;
            }

            var source = new Uri(BannerBaseModel.BannerPath + remotePath);
            var target = "ms-appdata:///local/" + this.seriesID.ToString() + "/" + fileName;

            var folder = await ApplicationData.Current.LocalFolder.CreateFolderAsync(this.seriesID.ToString(), CreationCollisionOption.OpenIfExists);
            
            var file = await folder.TryGetItemAsync(fileName);
            if (file != null)
            {
                var prop = await file.GetBasicPropertiesAsync();
                if (prop.Size > 0)
                {
                    return target;
                }
            }

            file = await folder.CreateFileAsync(fileName, CreationCollisionOption.ReplaceExisting);
            var downloader = new BackgroundDownloader();
            var op = downloader.CreateDownload(source, (StorageFile)file);
            await op.StartAsync();

            return target;
        }
    }
}
